<template>
  <div class="upload">
    <el-upload
      class="uploader"
      :action="uploadUrl"
      :name="name"
      :multiple="true"
      :accept="accept"
      :disabled="disabled"
      :limit="limit"
      :before-upload="handleBeforeUpload"
      :on-success="handleFileSuccess"
      :on-error="handleFileError"
      :on-preview="handlePreview"
      :on-remove="handleRemove"
      :file-list="fileList"
    >
      <i class="el-icon-upload" />
      <div class="el-upload__text"><em>点击上传</em></div>
      <div slot="tip" class="el-upload__tip">只能上传{{ limit }}个{{ accept }}文件，且不超过{{ size }}M</div>
    </el-upload>
    <el-dialog :visible.sync="dialogVisible" append-to-body>
      <img v-if="isImage(dialogImageUrl)" width="100%" :src="dialogImageUrl" alt="">
      <a v-else :href="dialogImageUrl">{{ dialogImageUrl }}</a>
    </el-dialog>
  </div>
</template>

<script>
import { Notification } from 'element-ui'

export default {
  name: 'UploadMultipleFiles',
  props: {
    value: {
      type: String,
      default: ''
    },
    /** 上传的文件字段名 */
    name: {
      type: String,
      default: ''
    },
    /** 接受上传的文件类型 */
    accept: {
      type: String,
      default: ''
    },
    /** 最大允许上传个数,默认无限制 */
    limit: {
      type: Number,
      default: 0
    },
    /** 是否禁用,默认false */
    disabled: {
      type: Boolean,
      default: false
    },
    /** 最是否禁用,默认2M */
    size: {
      type: Number,
      default: 5
    }
  },
  data() {
    return {
      uploadUrl: this.domain + '/nt/upload/operationfile',
      dialogImageUrl: '',
      dialogVisible: false,
      fileList: []
    }
  },
  watch: {
    value() {
      if (this.value !== '') {
        this.fileList = this.value.split(',').map(item => {
          const obj = {}
          obj.url = item
          obj.name = item.split('%').pop()
          return obj
        })
      }
    }
  },
  created() {
    if (this.value !== '') {
      this.fileList = this.value.split(',').map(item => {
        const obj = {}
        obj.url = item
        obj.name = item.split('%').pop()
        return obj
      })
    }
  },
  methods: {
    handleInput(value) {
      this.fileList = value
      const list = value.map(item => {
        return item.url
      })
      this.$emit('input', list.join(','))
    },
    // 上传成功回调
    handleFileSuccess(response, file, fileList) {
      if (response.code !== 20000) {
        this.$message.error('上传失败,请重新上传')
      } else {
        file.url = response.data
        this.handleInput(fileList)
      }
    },
    // 删除上传图片
    handleRemove(file, fileList) {
      this.handleInput(fileList)
    },
    // 上传失败回调
    handleFileError() {
      this.$message.error('上传失败,请重新上传')
      return false
    },
    isImage(url) {
      return /\.(jpeg|jpg|png|gif)$/i.test(url)
    },
    // 上传文件之前处理
    handleBeforeUpload(file) {
      if (this.accept === 'xls/xlsx') {
        if (file.type !== 'application/vnd.ms-excel' && file.type !== 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet') {
          Notification.error({
            title: '错误',
            message: '请上传' + this.accept + '类型文件'
          })
          return false
        }
      }
      if (file.size / 1024 / 1024 > this.size) {
        Notification.error({
          title: '错误',
          message: '上传文件大小不能超过' + this.size + 'MB'
        })
        return false
      }
      if (this.limit > 0 && this.fileList.length >= this.limit) {
        Notification.error({
          title: '错误',
          message: '最多只能上传' + this.limit + '个文件'
        })
        return false
      }
    },
    // 点击文件列表中已上传的文件时的钩子
    handlePreview(file) {
      const url = this.domain + file.url
      console.log('下载地址 -> ' + url)
      window.open(url)
    }
  }
}
</script>

<style lang="scss" scoped>
.upload >>> .el-dialog__header {
  background-color: initial;
}
.upload >>> .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.upload {
  .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .uploader .el-upload:hover {
    border-color: #409EFF;
  }
  .uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 148px;
    height: 148px;
    line-height: 148px;
    text-align: center;
  }
  .image-preview {
    width: 148px;
    max-height: 148px;
    display: block;
  }
}
</style>
